package com.itcg.springboot01change.service.impl;

import com.itcg.springboot01change.mapper.AccountMapper;
import com.itcg.springboot01change.pojo.Account;
import com.itcg.springboot01change.pojo.Page;
import com.itcg.springboot01change.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void insert(Account account) {
        accountMapper.insert(account);
    }

    @Override
    public void delete(Integer id) {
        accountMapper.delete(id);
    }

    @Override
    public void update(Account account) {
        accountMapper.update(account);
    }

    /**
     * 查询所有账户
     *
     * @return
     */
    @Override
    public List<Account> selectAll() {
        return accountMapper.selectAll();
    }

    @Override
    public Account selectById(Integer id) {
        return accountMapper.selectById(id);
    }

    @Override
    public Account selectByName(String name) {
        return accountMapper.selectByName(name);
    }

    @Override
    @Transactional
    public void transfer(String inName, String outName, Double money) {
        Account InAccount = accountMapper.selectByName(inName);
        Account OutAccount = accountMapper.selectByName(outName);

        InAccount.setMoney(InAccount.getMoney() - money);
        OutAccount.setMoney(OutAccount.getMoney() + money);

        accountMapper.update(InAccount);
        //int a = 1/0;
        accountMapper.update(OutAccount);
    }

    @Override
    public List<Account> finaPageAccount(String homeAddress, Integer pageNum, Integer pageSize) {
        Page<Account> page = new Page<>();
        //每页显示记录数
        page.setPageSize(pageSize);
        //当前页码
        page.setPageSize(pageNum);

        //起始索引
        Integer StartingIndex = (pageNum - 1) * pageSize;
        //设置当前页面数据
        List<Account> accounts = accountMapper.finaPageAccount(homeAddress, StartingIndex, pageSize);
        page.setDataList(accounts);
        return Collections.emptyList();
    }

    @Override
    public Long findCount(String homeAddress) {
        return accountMapper.findCount(homeAddress);
    }
}
